const Service = require("egg").Service;

class GradeService extends Service {
    /**
     * 班级列表
     */
    async readList() {
        let sql = `
            select 
                g.id as grade_id, 
                g.name as grade_name, 
                g.rid as room_id, 
                r.name as room_name, 
                g.sid as subject_id, 
                s.name as subject_name
            from grade as g
            join room as r on g.rid = r.id
            join subject as s on g.sid = s.id;
        `;
        let res = await this.app.mysql.query(sql);
        return res;
    }

    /**
     * 根据班级id，查找某个班级
     * @param {string} id 班级id
     */
    async find(id) {
        let sql = "select * from grade where id = ? limit 0, 1";
        let params = [id];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 添加班级
     */
    async add({ name, rid, sid }) {
        // 检查教室是否存在
        const room = await this.service.room.find(rid);
        if (!room) {
            this.ctx.cast(404, "该教室不存在");
        }
        // 检查课程是否存在
        const subject = await this.service.subject.find(sid);
        if (!subject) {
            this.ctx.cast(404, "该课程不存在");
        }
        // 入库
        let sql = "insert into grade (id, name, rid, sid) values (?, ?, ?, ?)";
        let params = [this.ctx.helper.uuid(), name, rid, sid];
        let res = await this.app.mysql.query(sql, params);
        return {
            id: res.insertId,
            rows: res.affectedRows,
        };
    }
}

module.exports = GradeService;
